import { request } from "../../request/index.js";
// pages/address_list/index.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    addressArray: {},
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // 1 获取缓存中的收货地址信息
    const addressArray = wx.getStorageSync("addressArray");
    this.setData({ addressArray });
  },
  // 删除收货地址
  deleteAddress(e) {
    console.log("e", e.currentTarget.dataset.id);
    let id = e.currentTarget.dataset.id;
    wx.showModal({
      title: "提示",
      content: "确定要删除吗？",
      success: async function (sm) {
        if (sm.confirm) {
          // 用户点击了确定 可以调用删除方法了
          try {
            const res = await request({
              url: `/v2/address/${id}`,
              method: "DELETE",
            });
            if (res.status == 200) {
              wx.showModal({
                title: "删除成功！", // 标题
                icon: "success", // 图标类型，默认success
                duration: 1000, // 提示窗停留时间，默认1500ms
              });
              this.handleChooseAddress();
            } else {
              wx.showModal({
                title: "删除失败！", // 标题
                icon: "none", // 图标类型
                duration: 1000, // 提示窗停留时间，默认1500ms
              });
            }
          } catch (error) {
            console.log(error);
          }
        } else if (sm.cancel) {
          console.log("用户点击取消");
        }
      },
    });
  },
  // 获取收货地址
  async handleChooseAddress() {
    try {
      const res = await request({ url: "/v2/address" });
      this.setData({ addressArray: res });
      // 5 存入到缓存中
      wx.setStorageSync("addressArray", res);
    } catch (error) {
      console.log(error);
    }
  },
  // 选择收货地址
  async chooseAddrses(e) {
    console.log('e',e.currentTarget.dataset.id);
    let id = e.currentTarget.dataset.id
    try {
      const res = await request({ url: `/v2/address/${id}` });
      // 5 存入到缓存中
      wx.setStorageSync("address", res);
      console.log('111');
      wx.navigateTo({
        url: "/pages/cart/index",
      });
      console.log('跳转到购物车');
    } catch (error) {
      console.log(error);
    }
  }
});
